<?php
namespace Backend\Controllers;

use Commons\App;

class UploadController extends BaseController
{

    public function initialize()
    {
        parent::initialize();
    }

    public function imageAction()
    {
        $filed = isset($_POST['filed']) ? $_POST['filed'] : 'file';
        if (!isset($_FILES[$filed])) {
            return $this->json([
                'code' => 401,
                'msg'  => '上传错误，没有找到上传文件！'
            ]);
        }
        $config   = App::globalConfig();
        $dir      = date('ym');
        $savePath = $config->application->uploadPath;
        $saveUrl  = $config->application->assetsUri;
        $savePath = rtrim($savePath, '/') . '/activity/' . $dir . '/';
        $saveUrl  = rtrim($saveUrl, '/') . '/activity/' . $dir . '/';
        if (!file_exists($savePath)) {
            if (!mkdir($savePath)) {
                return $this->json([
                    'code' => 401,
                    'msg'  => '上传目录不存在！' . $savePath
                ]);
            }
        }
        if (is_dir($savePath) === false) {
            return $this->json([
                'code' => 401,
                'msg'  => '上传目录不存在！' . $savePath
            ]);
        }
        if (is_writable($savePath) === false) {
            return $this->json([
                'code' => 401,
                'msg'  => '上传目录权限错误!'
            ]);
        }
        $info = pathinfo($_FILES[$filed]['name']);
        $ext  = strtolower($info['extension']);
        $exts = ['jpg', 'png', 'gif'];
        if (!empty($exts) && is_array($exts) && count($exts) > 0) {
            if (!in_array($ext, $exts)) {
                return $this->json([
                    'code' => 401,
                    'msg'  => '上传错误，文件扩展名不被允许！'
                ]);
            }
        } else {
            return $this->json([
                'code' => 401,
                'msg'  => '上传错误，被允许上传的文件扩展名配置丢失！'
            ]);
        }
        $newName  = date("dHis") . mt_rand(10, 99) . '.' . $ext;
        $savePath = $savePath . $newName;
        $saveUrl  = $saveUrl . $newName;
        if (move_uploaded_file($_FILES[$filed]['tmp_name'], $savePath) === false) {
            return $this->json([
                'code' => 401,
                'msg'  => '系统错误，上传文件失败'
            ]);
        }
        chmod($savePath, 0644);
        if ($ext != 'mp3') {
            $fileInfo = getimagesize($savePath);
            if ($fileInfo === false) {
                return $this->json([
                    'code' => 401,
                    'msg'  => '系统错误，获取文件信息失败！'
                ]);
            }
        }
        $this->json([
            'code' => 200,
            'url'  => $saveUrl
        ]);
    }

}
